import config from '@/config'
import storage from '@/utils/storage'
import constant from '@/utils/constant'
import { login, logout, getInfo } from '@/api/login'
import { setToken, removeToken, setTenantId, getTenantId } from '@/utils/auth'
import MQTT from "@/utils/mqtt";

const baseUrl = config.baseUrl

const user = {
  state: {
    name: storage.get(constant.name),
    avatar: storage.get(constant.avatar),
    roles: storage.get(constant.roles),
    permissions: storage.get(constant.permissions),
    tenantName: storage.get(constant.tenantName),
    id: storage.get(constant.id),
    tenantId: storage.get(constant.tenantId),
    dataPermission:storage.get(constant.dataPermission),
  },
  mutations: {

    SET_NAME: (state, name) => {
      state.name = name
      storage.set(constant.name, name)
    },
    SET_TENANT_NAME: (state, tenantName) => {
      state.tenantName = tenantName
      storage.set(constant.tenantName, tenantName)
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
      storage.set(constant.avatar, avatar)
    },
    SET_TENANTID: (state, tenantId) => {
      state.tenantId = tenantId
      storage.set(constant.tenantId, tenantId)
    },
    SET_ID: (state, id) => {
      state.id = id
      storage.set(constant.id, id)
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
      storage.set(constant.roles, roles)
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions
      storage.set(constant.permissions, permissions)
    },
    SET_DATA_PERMISSION: (state, dataPermission) => {
      state.dataPermission = dataPermission
      storage.set(constant.dataPermission, dataPermission)
    }
  },

  actions: {
    // 登录
    Login({ commit, dispatch }, userInfo) {
      const mobile = userInfo.mobile
      const password = userInfo.password
      const captchaVerification = userInfo.captchaVerification
      return new Promise((resolve, reject) => {
        login(mobile, password, captchaVerification).then(res => {
          res = res.data;
          // 设置 token
          setToken(res)
          // 设置租户Id
          setTenantId(res.tenantId)
          dispatch('HandleSubscribeAlarm')
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户信息
    GetInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        getInfo().then(res => {
          res = res.data; // 读取 data 数据
          const dataPermission = res.dataPermission
          const user = res.user
          const avatar = (user == null || user.avatar === "" || user.avatar == null) ? require("@/static/images/profile.jpg") : user.avatar
          const nickname = (user == null || user.nickname === "" || user.nickname == null) ? "" : user.nickname

          const tenantName = (user == null || user.tenantName === "" || user.tenantName == null) ? "" : user.tenantName
          const tenantId = user.tenantId
          const id = user.id

          // const tenantId = user.tenantId

          if (res.roles && res.roles.length > 0) {
            commit('SET_ROLES', res.roles)
            commit('SET_PERMISSIONS', res.permissions)
          } else {
            commit('SET_ROLES', ['ROLE_DEFAULT'])
          }
          commit('SET_DATA_PERMISSION', dataPermission)

          commit('SET_NAME', nickname)
          console.log('tenantName>>>>>',tenantName)
          commit('SET_TENANT_NAME', tenantName)
          commit('SET_AVATAR', avatar)
          commit('SET_ID', id)
          commit('SET_TENANTID', tenantId)
          resolve(res)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 退出系统
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          commit('SET_ROLES', [])
          commit('SET_PERMISSIONS', [])
          commit('SET_DATA_PERMISSION', {})
          removeToken()
          storage.clean()
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 订阅报警消息
    HandleSubscribeAlarm({ commit, state }) {
      const tenantId = getTenantId()
      let it = MQTT.getInstance();
      const topic = `iot/${tenantId}/thing/event/post`
      it.subscribe(topic, 0);
      it.set_message_callback(
          topic,
          (topic, payload) => {
            const data = JSON.parse(payload.toString())
            console.log('%c [ data ]-141', 'font-size:13px; background:#bff4e2; color:#ffffff;', data)
            var pages = getCurrentPages()
            if(pages[pages.length - 1].route.indexOf('pages/devices/detail/index') > -1)
              return
            if (data.level === 0)
              return
            if (state.dataPermission.all || state.dataPermission?.deptIds?.includes(data.orgId)) {
							uni.$emit('refresh-police-list',true)
              uni.$popup.show({
                type:4,
                closeOpacity:true,
                mqttMessage: data,
                confirm: ()=>{
                  uni.navigateTo({
                    url:'/pages/devices/detail/index?deviceId='+data.deviceId
                  })
                }
              })
            }
          },
      )
    }
  }
}

export default user
